package com.example.emos.wx.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.emos.wx.config.exception.EmosException;
import com.example.emos.wx.db.dao.TbDeptDao;
import com.example.emos.wx.db.dao.TbUserDao;
import com.example.emos.wx.db.pojo.TbUser;
import com.example.emos.wx.db.pojo.mq.MessageEntity;
import com.example.emos.wx.service.UserService;
import com.example.emos.wx.task.MessageTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @ClassName UserServiceImpl
 * @Author zhangzhixi
 * @Description
 * @Date 2022/8/26 11:38
 * @Version 1.0
 */
@SuppressWarnings("all")
@Service
@Slf4j
@Scope("prototype")
public class UserServiceImpl implements UserService {
    /**
     * 管理员用户邀请码
     */
    private static final String INVITATION_CODE = "000000";

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Autowired
    private TbDeptDao deptDao;

    @Autowired
    private TbUserDao userDao;

    @Autowired
    private MessageTask messageTask;

    /**
     * 发送POST请求，获取用户的OPENID(用户的唯一表示)
     *
     * @param code 用户的微信；临时授权码
     * @return openId
     */
    private String getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(response);
        String openId = json.getStr("openid");
        if (openId == null || openId.length() == 0) {
            throw new RuntimeException("临时登陆凭证错误");
        }
        return openId;
    }

    @Override
    public Integer login(String code) {
        // 通过临时授权字符串获取OpenId
        String openId = getOpenId(code);
        // 查询用户是否存在，
        Integer id = userDao.searchIdByOpenId(openId);
        if (id == null) {
            throw new EmosException("帐户不存在");
        }
        //从消息队列中接收消息，转移到消息表
//        messageTask.receiveAysnc(id + "");// 设置登录到首页发送轮询请求，不需要等待五秒钟
        return id;
    }

    @Override
    public TbUser searchById(int userId) {
        return userDao.searchById(userId);
    }

    @Override
    public String searchUserHiredate(int userId) {
        return userDao.searchUserHiredate(userId);
    }

    @Override
    public HashMap<String, Object> searchUserSummary(int userId) {
        return userDao.searchUserSummary(userId);
    }


    @Override
    public int registerUser(String registerCode, String code, String nickname, String photo) {
        //如果邀请码是000000，代表是超级管理员
        if (INVITATION_CODE.equals(registerCode)) {
            //查询超级管理员帐户是否已经绑定
            boolean bool = userDao.haveRootUser();
            if (!bool) {
                //把当前用户绑定到ROOT帐户
                String openId = getOpenId(code);
                HashMap<String, Object> param = new HashMap<>(16);
                param.put("openId", openId);
                param.put("nickname", nickname);
                param.put("photo", photo);
                param.put("role", "[0]");
                param.put("status", 1);
                param.put("createTime", new Date());
                param.put("root", true);
                userDao.insert(param);
                Integer id = userDao.searchIdByOpenId(openId);
                // 向MongoDB保存消息数据
                MessageEntity entity = new MessageEntity();
                entity.setSenderId(0);
                entity.setSenderName("系统消息");
                entity.setUuid(IdUtil.simpleUUID());
                entity.setMsg("欢迎您注册成为超级管理员，请及时更新你的员工个人信息。");
                entity.setSendTime(new Date());
                messageTask.sendAsync(id + "", entity);

                return id;
            } else {
                //如果root已经绑定了，就抛出异常
                throw new EmosException("无法绑定超级管理员账号");
            }
        }
        //TODO 此处还有其他判断内容
        else {
            return 0;
        }
    }

    @Override
    public Set<String> searchUserPermissions(int userId) {
        return userDao.searchUserPermissions(userId);
    }

    @Override
    public ArrayList<HashMap> searchUserGroupByDept(String keyword) {
        /*按照部门分组查询部门成员*/
        ArrayList<HashMap> list_1 = deptDao.searchDeptMembers(keyword);
        /*查询员工列表，按照部门分组排列*/
        ArrayList<HashMap> list_2 = userDao.searchUserGroupByDept(keyword);

        for (HashMap map_1 : list_1) {
            long deptId = (Long) map_1.get("id");
            /*一个部门*/
            ArrayList members = new ArrayList();
            for (HashMap map_2 : list_2) {
                long id = (Long) map_2.get("deptId");
                if (deptId == id) {
                    /*将一个分组内的数据添加到集合里面*/
                    members.add(map_2);
                }
            }
            /*一个部门的数据*/
            map_1.put("members", members);
        }

        return list_1;
    }

    @Override
    public ArrayList<HashMap> searchMembers(List param) {
        ArrayList<HashMap> list = userDao.searchMembers(param);
        return list;
    }

    @Override
    public List<HashMap> selectUserPhotoAndName(List param) {
        return userDao.selectUserPhotoAndName(param);
    }

    /**
     * 获取用户签名字符串
     *
     * @param id 用户id
     * @return 以用户邮箱为用户签名字符串
     */
    @Override
    public String searchMemberEmail(int id) {
        String email = userDao.searchMemberEmail(id);
        return email;
    }
}
